package com.qty.apkviewer

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsetsController
import android.widget.AdapterView
import android.widget.ListView
import androidx.lifecycle.Observer
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.qty.apkviewer.activities.ApkInfoActivity
import com.qty.apkviewer.adapter.ApkViewerAdapter
import com.qty.apkviewer.log.QLog
import com.qty.apkviewer.model.ApkInfo
import com.qty.apkviewer.sp.SharedPreferencesHelper
import com.qty.apkviewer.utils.Constants
import com.qty.apkviewer.utils.PermissionUtils
import com.qty.apkviewer.worker.QueryAllPackagesWorker
import java.util.concurrent.TimeUnit

class ApkViewer : BaseActivity(), AdapterView.OnItemClickListener {

    private lateinit var listView: ListView

    private lateinit var mSharedPreferencesHelper: SharedPreferencesHelper
    private lateinit var apkViewerAdapter: ApkViewerAdapter
    private val allPackages = ArrayList<ApkInfo>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_apk_viewer)

        mSharedPreferencesHelper = SharedPreferencesHelper.getInstance(this)
        val emptyView = layoutInflater.inflate(R.layout.empty_list_view, null)
        emptyView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        emptyView.visibility = View.GONE

        listView = findViewById(R.id.apk_list)
        (listView.parent as ViewGroup).addView(emptyView)
        listView.emptyView = emptyView
        listView.onItemClickListener = this
        apkViewerAdapter = ApkViewerAdapter(this, ArrayList())
        listView.adapter = apkViewerAdapter

        // 如果应用是第一次启动，则申请应用所有权限，否则只申请当前页面需要的权限
        val firstUse = mSharedPreferencesHelper.isFirstUse()
        QLog.i(this, "onCreate=>firstUse: $firstUse")
        if (firstUse) {
            mSharedPreferencesHelper.setNotFirstUse()
            if (PermissionUtils.checkAllPermissions(this)) {
                initListView()
            } else {
                PermissionUtils.requstAllPermissions(this) {
                    if (PermissionUtils.checkQueryAllPackagePermission(this)) {
                        initListView()
                    } else {
                        finish()
                    }
                }
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (PermissionUtils.checkQueryAllPackagePermission(this)) {
                    initListView()
                } else {
                    PermissionUtils.requestQueryAllPackagesPermission(this) { graint ->
                        QLog.d(this@ApkViewer, "onCreate=>Request query all packages permission: $graint")
                        if (graint) {
                            initListView()
                        } else {
                            QLog.e(this@ApkViewer, "onCreate=>Query all packages permission is denied.")
                            finish()
                        }
                    }
                }
            } else {
                initListView()
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.apk_viewer_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.refresh -> {
                initListView()
                true
            }
            R.id.system_app -> {
                QLog.d(this, "onOptionsItemSelected=>system app....")
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    window.insetsController?.setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)
                } else {
                    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        val info = apkViewerAdapter.getItem(position)
        val apkInfoIntent = Intent(this, ApkInfoActivity::class.java)
        apkInfoIntent.putExtra(Constants.EXTRA_APK_NAME, info.name)
        apkInfoIntent.putExtra(Constants.EXTRA_APK_PACKAGE, info.packageName)
        apkInfoIntent.putExtra(Constants.EXTRA_APK_MAIN_CLASSNAME, info.mainClassName)
        startActivity(apkInfoIntent)
    }

    private fun initListView() {
        val workManager = WorkManager.getInstance(this)
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
            .setRequiresBatteryNotLow(false)
            .setRequiresCharging(false)
            .setRequiresDeviceIdle(false)
            .setRequiresStorageNotLow(false)
            .build()
        val request = OneTimeWorkRequestBuilder<QueryAllPackagesWorker>()
            .setConstraints(constraints)
            .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.SECONDS)
            .build()
        workManager.cancelWorkById(request.id)
        workManager.enqueue(request)
        workManager.getWorkInfoByIdLiveData(request.id).observe(this, Observer {
            if (it.state == WorkInfo.State.SUCCEEDED) {
                allPackages.clear()
                allPackages.addAll(QueryAllPackagesWorker.apks)
                apkViewerAdapter.setApkInfos(allPackages)
            } else if (it.state == WorkInfo.State.FAILED) {
            }
        })
    }

}